#!/usr/bin/env bash

set -euo pipefail

if [[ "${1-}" == "-h" || ${1-} == "--help" ]];then
  echo "Using speedmgmt, build the helm chart for the latest version of Speedscale."
  echo "Set \$VERSION to explicitly set the chart version."
  exit 0
fi

# always run from this dir
cd "$(dirname "$0")"

# get the latest chart version from the existing tarballs
CURRENT_VERSION=$(ls speedscale-operator-*.tgz | sort -V | tail -n 1 | grep -oE '[0-9]+\.[0-9]+\.[0-9]+')
# create the next version of the chart by bumping the last digit
BUMPED_VERSION=$(echo "$CURRENT_VERSION" | awk -F. '{$NF = $NF + 1} 1' | sed 's/ /./g')
VERSION=${VERSION:-$BUMPED_VERSION}

echo "last chart version: $CURRENT_VERSION"
echo "new chart version:  $VERSION"

# generate the helm chart
echo "generating chart..."
speedmgmt generate helm "$VERSION" > /dev/null
if [[ -z "$VERSION" ]];then
  echo "It looks like you're missing a required binary.  This script is intended for Speedscale engineers.  Use the helm command to interact with charts."
  exit 1
fi

# ensure we support the image tag
IMAGE_TAG=$(yq .image.tag "${VERSION}/values.yaml")
echo "verifying image tag ${IMAGE_TAG}..."

# checking for the image version install script is a hacky way
# to ensure we have released this version
curl -sf "https://downloads.speedscale.com/speedctl/${IMAGE_TAG}/install" > /dev/null

# use the chart's README as this repo's README
cp "${VERSION}/README.md" .

# add a sample values file for the user to copy
cp "${VERSION}/values.yaml" .

# bundle it up
echo "packaging chart..."
helm package "${VERSION}"

# update index yaml
helm repo index . --merge index.yaml --url https://speedscale.github.io/operator-helm/

echo "
Excellent, you've built the helm chart from the latest version of speedmgmt.
Now we need to update speedscale/partner-charts and submit a PR to the upstream
rancher/partner-charts.

Update the fork branch of speedscale/partner-charts with 'git pull https://github.com/rancher/partner-charts main-source'

Details at https://github.com/rancher/partner-charts/tree/main-source.

The commands should look something like this:
$ vim packages/speedscale-operator/package.yaml # to bump the URL and packageVersion
$ PACKAGE=speedscale-operator make prepare
$ make validate
$ # git commit and push one or more times
$ make validate
$ make clean
$ submit PR
"
